<template>
    <div>
        <Row :gutter="20" class="margin-bottom-20">
            <i-col :span="6">
                <Select placeholder="人员标签" v-model="searchModel.tenant_tag_id" clearable>
                    <Option v-for="item in tags" :value="item.id" :key="item.id">
                        {{item.name}}
                    </Option>
                </Select>
            </i-col>
            <i-col :span="5">
                <i-input placeholder="姓名/手机号码" v-model="searchModel.keyword" @keydown.enter.native="handleSearch"></i-input>
            </i-col>
            <i-button @click="handleSearch">搜索</i-button>
        </Row>
        <Table
            :columns="columns"
            :data="tableData"
            :loading="loading">
        </Table>
        <div class="text-center margin-top-20">
            <Page
                show-total
                :current.sync="pagination.current"
                :total="pagination.total"
                :page-size="pagination.limit"
                @on-change="initData"
            />
        </div>

        <member-detail
            :visible.sync="memberDetail.visible"
            :user-id="memberDetail.userId"
            :role-id="memberDetail.roleId">
        </member-detail>
    </div>
</template>

<script>
    /**
     * 房源 - 门禁出入异常
     */
    import debounce from 'lodash/debounce'
import { http, api } from '@/libs/http'
import { dayjs, date, dayTimeStamp } from '@/libs/date'
import { memberDetail } from '@/components'

export default {
      name: 'home-access-control-open-history',
      props: {
        deviceInfo: Object,
        homeId: Number
      },
      components: {
        memberDetail
      },
      created () {
        this.fetchTags()
        this.initData()
      },
      data () {
        return {
          loading: false,
          tableData: [],
          tags: [],
          memberDetail: {
            userId: 0,
            roleId: 2,
            visible: false
          },
          columns: [
            {
              title: '开门人',
              render: (h, { row }) => {
                return <a href='javascript:;' onClick={() => this.handleMemberDetail(row)}>{row.user}</a>
              }
            },
            { title: '预警原因', key: 'reason' },
            { title: '最后一次开门时间', key: 'lastOpenTime' },
            { title: '创建时间', key: 'createTime' },
            {
              title: '操作',
              render: (h, p) => {
                return <i-button size='small' onClick={() => this.handleReleaseAlert(p.row)}>解除预警</i-button>
              }
            }
          ],
          pagination: {
            current: 1,
            total: 0,
            limit: 20
          },
          searchModel: {
            tenant_tag_id: '',
            keyword: ''
          }
        }
      },
      methods: {
        handleReleaseAlert (record) {
          this.$Modal.confirm({
            loading: true,
            title: '提示',
            content: '确定解除预警?',
            onOk: () => {
              this.releaseAlert(record.id, record.home.id)
            }
          })
        },
        async releaseAlert (tenant_id, home_id) {
          try {
            const params = { tenant_id, home_id }
            const res = await http.req(api.face_access_del_exception_tenants, null, params)
            if (res) {
              this.$Message.success('解除成功')
              this.initData()
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.$Modal.remove()
          }
        },
        async fetchTags () {
          try {
            const res = await http.req(api.tenant_tags_get, null, { limit: 100, is_unopened_warn: 1 })
            if (res) this.tags = res.rows
          } catch (err) {
            console.log(err)
          }
        },
        async handleMemberDetail (record) {
          this.memberDetail.userId = record.id
          this.memberDetail.visible = true
        },
        handleSearch: debounce(function () {
          this.pagination.current = 1
          this.initData()
        }),
        generateQuery () {
          const { current, limit } = this.pagination
          const { tenant_tag_id, keyword } = this.searchModel
          const query = {
            limit,
            home_id: this.homeId,
            tenant_tag_id: tenant_tag_id || null,
            offset: (current - 1) * limit
          }
          if (keyword) {
            if (/^\d+$/g.test(keyword)) {
              query.phone = keyword
            } else {
              query.name = keyword
            }
          }
          return query
        },
        async initData () {
          try {
            this.loading = true
            const query = this.generateQuery()
            const res = await http.req(api.tenant_access_error, null, query)
            if (res) {
              res.rows.forEach(record => {
                const { name, last_open_access_time, tenant_tag: { name: tagName, unopened_warn_num } } = record
                record.reason = this.getReason(last_open_access_time)
                record.user = `[${tagName}]${name}`
                record.createTime = date(dayjs(last_open_access_time).valueOf() + Number(unopened_warn_num) * dayTimeStamp, 'YYYY-MM-DD HH:mm')
                record.lastOpenTime = date(last_open_access_time, 'YYYY-MM-DD HH:mm')
              })
              this.pagination.total = res.count
              this.tableData = res.rows
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },

        // 返回开门记录文案
        getReason (lastOpenTime) {
          let diff = dayjs().valueOf() - dayjs(lastOpenTime).valueOf()
          diff = Math.floor(diff / (24 * 60 * 60 * 1000))
          return '超过' + diff + '天没有开门记录'
        }
      }
    }
</script>
